<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">
          <el-form-item label="客户名称">
            <el-input v-model="listQuery.customerName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="客户人员">
            <el-input v-model="listQuery.customerUserName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="会面内容">
            <el-input v-model="listQuery.talkText"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>

        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini"
                     @click="reset" type="info">重置
          </el-button>
          <el-button size="mini"
                     type="success" @click="handleCreate">新增
          </el-button>
        </div>
      </template>
    </search-box>


      <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>

        <el-table-column prop="customerName"
                         label="客户名称">
        </el-table-column>

        <el-table-column prop="customerUserName"
                         label="客户人员">
        </el-table-column>
        <el-table-column prop="customerAddress"
                         label="会面地址">
        </el-table-column>

        <el-table-column prop="userName"
                         label="会面人">
        </el-table-column>

        <el-table-column prop="talkTime"
                         label="会面时间">
        </el-table-column>

<!--        <el-table-column prop="talkText"-->
<!--                         label="会面内容">-->
<!--        </el-table-column>-->

        <el-table-column prop="talkTextUrl"
                         label="附件地址">
        </el-table-column>


        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>




    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="70%"
      style="margin-top: -5%"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">

        <el-form-item label="客户名称" prop="customerName">
          <el-select v-model="form.customerName" filterable placeholder="请选择">
            <el-option
              v-for="item in customerNameList"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.customerName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户人员" prop="customerUserName">
          <el-input v-model="form.customerUserName" ></el-input>
        </el-form-item>

        <el-form-item label="会面地址" prop="customerAddress">
          <el-input v-model="form.customerAddress" ></el-input>
        </el-form-item>


        <el-form-item label="会面人部门" prop="departmentName">
          <el-select v-model="form.departmentName" @change="getUsersList"
                         placeholder="请选择部门">
            <el-option v-for="item in departmentList"
                           :key="item.departmentName"
                           :label="item.departmentName"
                           :value="item.departmentName">
            </el-option>
          </el-select>

        </el-form-item>


        <el-form-item label="会面人" prop="userName">
          <el-select v-model="form.userName"
                         placeholder="请选择参会人员" multiple>
            <el-option v-for="item in usersList"
                           :key="item.userCode"
                           :label="item.userName"
                           :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="会面时间" prop="talkTime">
          <el-date-picker
            v-model="form.talkTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="会面内容" prop="talkText">
          <el-col :span="24">
            <quill-editor
              ref="text"
              v-model="form.talkText"
              class="myQuillEditor"
              :options="editorOption"
              rows="10"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="附件地址" prop="talkTextUrl">
          <el-input v-model="form.talkTextUrl" ></el-input>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="onSubmit" >确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as apiUser from '@/api/user'
  import * as customerTalk from '@/api/customer/customerTalk'
  import * as customerManage from '@/api/customer/customerManage'
  import * as myProject from '@/api/projectOa/myProject'
  import * as department from '@/api/system-setting/department'
  import * as position from '@/api/system-setting/position'
  import * as user from '@/api/system-setting/user'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import { MessageBox } from 'element-ui'
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'

  import { quillEditor } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {
    name: 'department',
    components: { Pagination, searchBox, quillEditor },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        total: 0,
        dialogVisible: false,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          departmentName: '',
          departmentName1: '',
          departmentCode: '',
          positionName: '',
          roleName: '',
          pageSize: 50,
          name: undefined,
          proPersonLiable: undefined,
          proDepartment: undefined,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        departmentList: [
        ],
        usersList: [
        ],
        listParent: [
        ],

        customerNameList: [
        ],

        editorOption: {},

        form: {},

        dialogTitle: '',

        userName: '',


        rulesList: [
          {label: '管理员', value: '管理员'},
          {label: '言川一级用户', value: '言川一级用户'},
          {label: '言川二级用户', value: '言川二级用户'},
          {label: '言川三级用户', value: '言川三级用户'},

        ],

        rules: {
          customerName: [{ required: true, message: '客户名称必选', trigger: 'blur' }],
          customerUserName: [{ required: true, message: '客户人员必填', trigger: 'blur' }],
          customerAddress: [{ required: true, message: '会面地址必填', trigger: 'blur' }],
          userName: [{ required: true, message: '会面人必选', trigger: 'blur' }],

        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {
      this.getList()
      this.getCustomerNameList()
      // this.getRoleList()
      this.getDepartmentList()
      // this.getDepartmentList1()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })

    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)

      // alert(this.$store.getters.selectedTenantId);
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: {
      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        this.listQuery.status = 1;
        const { content } = await customerTalk.getCustomerTalkInfoList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },


      async getListParent() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        const { content } = await myProject.getProjectListParent(this.listQuery)
        this.listParent = content;


      },



      async getDepartmentList() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList = content.list;

      },
      async getDepartmentList1() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList1 = content.list;

      },




      async getRoleList() { // 获取列表数据

        const { content } = await department.getRoleList(this.listQuery)
        this.rulesList = content.list;

      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleCreate() {
        this.form = {}
        this.dialogVisible = true
        this.dialogTitle = '访谈新增'
        this.listQuery = {};
        this.getListParent()
      },
      handleUpdate(row) {
        this.dialogVisible = true
        this.dialogTitle = '访谈编辑'
        this.form = row;
        this.form.userName = row.userName.split(',')
        this.getListParent()

      },

      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          customerTalk.deleteCustomerTalkInfo(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })

      },

      reset() {
        this.listQuery.customerName = ''
        this.listQuery.customerUserName = ''
        this.listQuery.talkText = ''
        this.getList()
      },
      cancel() {
        this.listQuery.customerName = ''
        this.listQuery.customerUserName = ''
        this.listQuery.talkText = ''
        this.dialogVisible = false;
        this.getList()
      },
      onSubmit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId

            let userName = ''
            for (let i = 0; i < this.form.userName.length; i++) {
              userName += (this.form.userName[i] + ',')
            }
            this.form.userName = userName.substring(0, userName.length - 1)

            this.form.status = 1;

            if(this.dialogTitle=='访谈新增'){
              customerTalk.createCustomerTalkInfo(this.form).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.customerName = ''
                  this.listQuery.customerUserName = ''
                  this.listQuery.talkText = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }else if(this.dialogTitle=='访谈编辑'){
              customerTalk.updateCustomerTalkInfo(this.form).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.customerName = ''
                  this.listQuery.customerUserName = ''
                  this.listQuery.talkText = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });

      }
,
      async getUsersList() { // 获取列表数据
        this.form.userName = ''
        this.usersList = []
        console.log('this.userName', this.userName)
        const { content } = await user.getUserListNoName(this.form)
        this.usersList = content

      },


      async getCustomerNameList() { // 获取列表数据
        this.customerNameList = []
        this.listQuery.status = 1
        const { content } = await customerManage.getCustomerManageInfoList(this.listQuery)
        this.customerNameList = content.list

      },


    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
